<template>
    <div class="app-container">
        <!--工具栏-->
        <div class="head-container">
            <div v-if="crud.props.searchToggle">
                <!-- 搜索 -->
                <el-input v-model="query.blurry" clearable size="small" placeholder="代理商名称/手机号码/联系地址/联系人模糊搜索" style="width: 330px;"
                                class="filter-item" @keyup.enter.native="toQuery" />
                <rrOperation :crud="crud"/>
            </div>
            <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
            <crudOperation :permission="permission"/>

            <!-- 文件上传 -->
            <el-dialog :visible.sync="dialog" :close-on-click-modal="false" append-to-body width="500px" @close="doSure">
                <el-upload
                :before-upload="beforeUpload"
                :before-remove="handleBeforeRemove"
                :on-success="handleSuccess"
                :on-error="handleError"
                :file-list="fileList"
                :headers="headers"
                :action="ossUploadApi"
                :limit="1"
                class="upload-demo"
                :multiple=false>
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" style="display: block;" class="el-upload__tip">上传文件的大小必须小于10M</div>
                </el-upload>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="doSure">确认</el-button>
                </div>
            </el-dialog>

            <!--表单组件-->
            <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                       :title="crud.status.title" width="500px">
                <el-form ref="form" :model="form" :rules="rules" size="small"
                         label-width="100px">
                                <el-form-item label="代理商名称" prop="agentName">
                                        <el-input v-model="form.agentName" style="width: 350px"/>
                                </el-form-item>
                                <el-form-item label="手机号码" prop="phone">
                                    <el-select v-model="form.phone" style="width: 350px" 
                                            placeholder="请选择手机号码" @change="getMemberUser" clearable filterable>
                                        <el-option
                                        v-for="(item, index) in users"
                                        :key="item.phone + index"
                                        :label="item.phone"
                                        :value="item.phone"
                                        />
                                    </el-select>
                                </el-form-item>
                                <el-form-item
                                        label="联系人" prop="contacts">
                                        <el-input v-model="form.contacts" style="width: 350px;"/>
                                </el-form-item>
                                <el-form-item
                                        label="联系地址">
                                        <el-input v-model="form.address" style="width: 350px;"/>
                                </el-form-item>
                                <el-form-item label="营业执照URL" prop="imgUrl">
                                        <div id="divUpload">
                                               <el-input class="filter-item" v-model="form.imgUrl" style="width: 270px;"/>&nbsp;&nbsp;
                                               <el-button class="filter-item" size="mini" type="primary" icon="el-icon-upload" @click="dialog = true">上传</el-button>  
                                        </div>
                                </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="text" @click="crud.cancelCU">取消</el-button>
                    <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
                </div>
            </el-dialog>
            <!--表格渲染-->
            <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
                      @selection-change="crud.selectionChangeHandler">
                <el-table-column type="selection" width="55"/>
                                <el-table-column v-if="columns.visible('agentName')"
                                                 prop="agentName"
                                                 label="代理商名称"/>
                                <el-table-column v-if="columns.visible('phone')"
                                                 prop="phone"
                                                 label="手机号码"/>
                                <el-table-column v-if="columns.visible('address')"
                                                 prop="address"
                                                 label="联系地址"/>
                                <el-table-column v-if="columns.visible('contacts')"
                                                 prop="contacts"
                                                 label="联系人"/>
                                <el-table-column v-if="columns.visible('imgUrl')" prop="imgUrl" label="营业执照预览图">
                                  <template slot-scope="{row}">
                                    <el-image
                                      :src="row.imgUrl"
                                      :preview-src-list="[row.imgUrl]"
                                      fit="contain"
                                      lazy
                                      class="el-avatar"
                                    >
                                      <div slot="error">
                                        <i class="el-icon-document" />
                                      </div>
                                    </el-image>
                                  </template>
                                </el-table-column>
                                <el-table-column v-if="columns.visible('createTime')"
                                                  prop="createTime"
                                                  label="创建时间"/>
                <!--
                <el-table-column v-permission="['admin','agentMember:edit','agentMember:del']" label="操作"
                                 width="150px" align="center">
                    <template slot-scope="scope">
                        <udOperation :data="scope.row" :permission="permission"/>
                    </template>
                </el-table-column>
                -->

                <el-table-column label="操作" width="160px" align="center" fixed="right">
                  <template slot-scope="scope">
                    <el-button size="mini" style="margin-right: 2px" type="text">
                      <router-link :to="'/agent/agentMember/' + scope.row.id">
                        编辑代理商成员
                      </router-link>
                    </el-button>
                  </template>
                </el-table-column>

            </el-table>
            <!--分页组件-->
            <pagination/>
        </div>
    </div>
</template>

<script>
    import { getAllMemberUser } from '@/api/memberUser'
    import { mapGetters } from 'vuex'
    import { getToken } from '@/utils/auth'
    import crudAgentMember from '@/api/agentMember'
    import CRUD, {crud, form, header, presenter} from '@crud/crud'
    import rrOperation from '@crud/RR.operation'
    import crudOperation from '@crud/CRUD.operation'
    import udOperation from '@crud/UD.operation'
    import pagination from '@crud/Pagination'
    import MaterialList from "@/components/material";

    // crud交由presenter持有
    const defaultCrud = CRUD({
        title: '代理商',
        url: 'api/agentMember',
        sort: 'id,desc',
        crudMethod: {...crudAgentMember}
    })
    const defaultForm = {id: null, pid: null, isDel: null, createTime: null, updateTime: null, agentName: null, phone: null, address: null, contacts: null, imgUrl: null, commissionRatio: 0}
    export default {
        name: 'AgentMember',
        components: {pagination, crudOperation, rrOperation, udOperation , MaterialList},
        mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
        computed: {
            ...mapGetters([
            'ossUploadApi'
            ])
        },
        data() {
            return {
                title: '代理商信息',
                users: [],
                isAdd: false,
                dialog: false,
                icon: 'el-icon-refresh',
                url: '', 
                headers: { 'Authorization': getToken() },
                dialogImageUrl: '', dialogVisible: false, fileList: [], files: [], newWin: null,
                permission: {
                    add: ['admin', 'agentMember:add'],
                    edit: ['admin', 'agentMember:edit'],
                    del: ['admin', 'agentMember:del']
                },
                rules: {
                    agentName: [
                        { required: true, message: '代理商名称不能为空', trigger: 'blur' },
                        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                    ], 
                    phone: [
                        { required: true, message: '手机号码不能为空', trigger: 'blur' },
                        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                    ]
                },
                queryTypeOptions: [
                    {
                        key: 'agentName',
                        display_name: '代理商名称'
                    }, 
                    {
                        key: 'phone',
                        display_name: '手机号码'
                    }
                ]
            }
        },
        created() {
          //初始化按钮显示或者隐藏
          this.crud.optShow = { add: true, edit: false, del: false, download: false }
        },
        watch: {
        },
        mounted:function(){ //在页面加载参数结束后执行某个函数
            this.$nextTick(function(){
                //调用需要执行的方法
                this.getMemberUser()
            })      
        },
        methods: {
            // 获取数据前设置好接口地址
            [CRUD.HOOK.beforeRefresh]() {
                const query = this.query
                if (query.type && query.value) {
                    this.crud.params[query.type] = query.value
                } else {
                    delete this.crud.params.agentName
                    delete this.crud.params.phone
                }
                return true
            }, // 新增与编辑前做的操作
            [CRUD.HOOK.afterToCU](crud, form) {
            },
            getMemberUser() {
                getAllMemberUser().then(res => {
                    this.users = res
                }).catch(() => { })
            },
            beforeUpload(file) {
                const isLimit = file.size / 1024 / 1024 < 10
                if (!isLimit) {
                    this.$message.error('上传文件的大小必须小于10MB!')
                }
                return isLimit
            },
            handleSuccess(response, file, fileList) {
                const uid = file.uid
                const id = response.id
                this.form.imgUrl = response.url
                this.files.push({ uid, id })
            },
            handleBeforeRemove(file, fileList) {
                this.form.imgUrl = ''
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url
                this.dialogVisible = true
            },
            // 监听上传失败
            handleError(e, file, fileList) {
                const msg = JSON.parse(e.message)
                this.crud.notify(msg.message, CRUD.NOTIFICATION_TYPE.ERROR)
            },
            // 刷新列表数据
            doSure() {
                this.fileList = []
                this.dialogVisible = false
                this.dialogImageUrl = ''
                this.dialog = false
                //this.crud.toQuery()
            }
        }
    }


</script>

<style scoped>
    .table-img {
        display: inline-block;
        text-align: center;
        background: #ccc;
        color: #fff;
        white-space: nowrap;
        position: relative;
        overflow: hidden;
        vertical-align: middle;
        width: 32px;
        height: 32px;
        line-height: 32px;
    }
    
    #divUpload {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
    }
</style>
